package demo.string;

public class ReverseStr {

    public static void main(String[] args) {
        char[] chars = "dog loves pig apple sheep".toCharArray();

        rotateWord(chars);
        System.out.println(chars);
    }

    public static void rotateWord(char[] chars) {
        if (chars == null || chars.length == 0) {
            return;
        }

        System.out.println(chars);
        reverse(chars, 0, chars.length - 1);
        System.out.println(chars);

        int l = -1;
        int r = -1;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] != ' ') {
                if (i == 0 || chars[i - 1] == ' ') {
                    l = i;
                }

                if (i == chars.length - 1 || chars[i + 1] == ' ') {
                    r = i;
                }

                if (l != -1 && r != -1) {
                    reverse(chars, l, r);
                    l = -1;
                    r = -1;
                }
            }

        }
    }

    public static void reverse(char[] chars, int start, int end) {
        char tmp = 0;
        while (start < end) {
            tmp = chars[start];
            chars[start] = chars[end];
            chars[end] = tmp;
            start++;
            end--;
        }
    }
}
